package org.jsola.hr.service.impl;

import com.alibaba.fastjson.JSON;
import org.jsola.core.Page;
import org.jsola.core.Result;
import org.jsola.hr.common.CacheKeyKit;
import org.jsola.hr.common.ExampleKit;
import org.jsola.hr.common.secret.common.SecureType;
import org.jsola.hr.common.secret.secure.DES3Secure;
import org.jsola.hr.common.secret.secure.SecureFactory;
import org.jsola.hr.constant.HrConstants;
import org.jsola.hr.dao.IDepInfoDAO;
import org.jsola.hr.dao.IOfferInfoDAO;
import org.jsola.hr.dao.IPositionInfoDAO;
import org.jsola.hr.dto.OfferInfoAddDTO;
import org.jsola.hr.dto.OfferInfoUpdateDTO;
import org.jsola.hr.entity.DepInfoDO;
import org.jsola.hr.entity.OfferInfoDO;
import org.jsola.hr.entity.PositionInfoDO;
import org.jsola.hr.exception.HrException;
import org.jsola.hr.query.OfferInfoQuery;
import org.jsola.hr.service.IOfferInfoService;
import org.jsola.hr.vo.OfferInfoListVO;
import org.jsola.hr.vo.OfferInfoVO;
import org.jsola.user.core.TokenUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author zhr
 */
@Service("hrOfferInfoServiceImpl")
public class OfferInfoServiceImpl implements IOfferInfoService {

    @Autowired
    private IOfferInfoDAO offerInfoDAO;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private IDepInfoDAO depInfoDAO;

    @Autowired
    private IPositionInfoDAO positionInfoDAO;

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public OfferInfoVO save(OfferInfoAddDTO offerInfoAddDTO, TokenUser tokenUser) {
        // 转DO
        OfferInfoDO offerInfoDO = offerInfoAddDTO.to(OfferInfoDO.class);
        // 保存
        offerInfoDO = save(offerInfoDO, tokenUser.getSiteId(), tokenUser.getUserId());
        return offerInfoDO.to(OfferInfoVO.class);
    }

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public int update(OfferInfoUpdateDTO offerInfoUpdateDTO, TokenUser tokenUser) {
        //转DO
        OfferInfoDO offerInfoDO = offerInfoUpdateDTO.to(OfferInfoDO.class);
        //根据主键更新，只更新非null值
        return updateByIdSelective(offerInfoDO, tokenUser.getSiteId(), tokenUser.getUserId());
    }

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public int deleteByIds(TokenUser tokenUser, String... offerInfoIds) {
        return logicalDeleteByIds(tokenUser.getSiteId(), tokenUser.getUserId(), (Object[]) offerInfoIds);
    }


    @Override
    public OfferInfoVO selectById(String offerInfoId, String siteId) {
        OfferInfoDO offerInfoDO = selectDOById(offerInfoId, siteId);
        if (offerInfoDO == null) {
            return null;
        }
        return offerInfoDO.to(OfferInfoVO.class);
    }

    @Override
    public List<OfferInfoListVO> select(OfferInfoQuery offerInfoQuery, String siteId) {
        List<OfferInfoDO> offerInfoDOList = selectDO(offerInfoQuery, siteId);
        if(CollectionUtils.isEmpty(offerInfoDOList)) {
            return offerInfoDOList == null ? null : new ArrayList<>();
        }
        return offerInfoDOList.stream()
                .map(offerInfoDO -> offerInfoDO.to(OfferInfoListVO.class))
                .collect(Collectors.toList());
    }

    @Override
    public int selectCount(OfferInfoQuery offerInfoQuery, String siteId) {
        Example example = buildExample(offerInfoQuery,siteId);
        return offerInfoDAO.selectCountByExample(example);
    }

    @Override
    public Page<OfferInfoListVO> selectPage(OfferInfoQuery offerInfoQuery, String siteId) {
        Example example = buildExample(offerInfoQuery,siteId);
        Page<OfferInfoDO> page = offerInfoDAO.selectPageByExample(example,
                offerInfoQuery.getPageNo(),
                offerInfoQuery.getPageSize());

        return page.to(OfferInfoListVO.class);
    }

    @Override
    public OfferInfoDO selectDOById(String offerInfoId, String siteId) {
        return listById(offerInfoId, siteId);
    }

    @Override
    public List<OfferInfoDO> selectDO(OfferInfoQuery offerInfoQuery, String siteId) {
        Example example = buildExample(offerInfoQuery,siteId);
        return offerInfoDAO.selectByExample(example);
    }


    /**
     * 根据查询参数，构建example

     * @param offerInfoQuery 查询参数
     * @param siteId 所属站点id
     * @return example
     */
    private Example buildExample(OfferInfoQuery offerInfoQuery, String siteId) {
        Example example = new Example(OfferInfoDO.class);
        example.and()
                .andEqualTo("valid", true)
                .andEqualTo("siteId", siteId);
        if (offerInfoQuery.getName() != null) {
            example.and().andLike("name", "%" + offerInfoQuery.getName() + "%");
        }
        if (offerInfoQuery.getGender() != null) {
            example.and().andEqualTo("gender", offerInfoQuery.getGender());
        }
        if (offerInfoQuery.getPhone() != null) {
            example.and().andLike("phone", "%" + offerInfoQuery.getPhone() + "%");
        }
        if (offerInfoQuery.getEmail() != null) {
            example.and().andLike("email", "%" + offerInfoQuery.getEmail() + "%");
        }
        if (offerInfoQuery.getEmailCopy() != null) {
            example.and().andLike("emailCopy", "%" + offerInfoQuery.getEmailCopy() + "%");
        }
        if (offerInfoQuery.getEmailSecret() != null) {
            example.and().andLike("emailSecret", "%" + offerInfoQuery.getEmailSecret() + "%");
        }
        if (offerInfoQuery.getExpiry() != null) {
            example.and().andEqualTo("expiry", offerInfoQuery.getExpiry());
        }
        if (offerInfoQuery.getExpiryDateStart() != null &&
                offerInfoQuery.getExpiryDateEnd() != null) {
            example.and().andBetween("expiryDate", offerInfoQuery.getExpiryDateStart(),
                    offerInfoQuery.getExpiryDateEnd());
        }
        if (offerInfoQuery.getEntryDateStart() != null &&
                offerInfoQuery.getEntryDateEnd() != null) {
            example.and().andBetween("entryDate", offerInfoQuery.getEntryDateStart(),
                    offerInfoQuery.getEntryDateEnd());
        }
        if (offerInfoQuery.getEmployType() != null) {
            example.and().andEqualTo("employType", offerInfoQuery.getEmployType());
        }
        if (offerInfoQuery.getInformalType() != null) {
            example.and().andEqualTo("informalType", offerInfoQuery.getInformalType());
        }
        if (offerInfoQuery.getProbation() != null) {
            example.and().andEqualTo("probation", offerInfoQuery.getProbation());
        }
        if (offerInfoQuery.getRegularDateStart() != null &&
                offerInfoQuery.getRegularDateEnd() != null) {
            example.and().andBetween("regularDate", offerInfoQuery.getRegularDateStart(),
                    offerInfoQuery.getRegularDateEnd());
        }
        if (offerInfoQuery.getDepId() != null) {
            example.and().andLike("depId", "%" + offerInfoQuery.getDepId() + "%");
        }
        if (offerInfoQuery.getPositionId() != null) {
            example.and().andLike("positionId", "%" + offerInfoQuery.getPositionId() + "%");
        }
        if (offerInfoQuery.getCompany() != null) {
            example.and().andLike("company", "%" + offerInfoQuery.getCompany() + "%");
        }
        if (offerInfoQuery.getRank() != null) {
            example.and().andLike("rank", "%" + offerInfoQuery.getRank() + "%");
        }
        if (offerInfoQuery.getHrbp() != null) {
            example.and().andLike("hrbp", "%" + offerInfoQuery.getHrbp() + "%");
        }
        if (offerInfoQuery.getCompanyId() != null) {
            example.and().andEqualTo("companyId", offerInfoQuery.getCompanyId());
        }
        if (offerInfoQuery.getSupervisor() != null) {
            example.and().andLike("supervisor", "%" + offerInfoQuery.getSupervisor() + "%");
        }
        if (offerInfoQuery.getManagerForm() != null) {
            example.and().andEqualTo("managerForm", offerInfoQuery.getManagerForm());
        }
        if (offerInfoQuery.getWorkCityId() != null) {
            example.and().andLike("workCityId", "%" + offerInfoQuery.getWorkCityId() + "%");
        }
        if (offerInfoQuery.getWorkCity() != null) {
            example.and().andLike("workCity", "%" + offerInfoQuery.getWorkCity() + "%");
        }
        if (offerInfoQuery.getEntryAddr() != null) {
            example.and().andLike("entryAddr", "%" + offerInfoQuery.getEntryAddr() + "%");
        }
        if (offerInfoQuery.getEntryContact() != null) {
            example.and().andLike("entryContact", "%" + offerInfoQuery.getEntryContact() + "%");
        }
        if (offerInfoQuery.getEntryPhone() != null) {
            example.and().andLike("entryPhone", "%" + offerInfoQuery.getEntryPhone() + "%");
        }
        if (offerInfoQuery.getCompanyAddr() != null) {
            example.and().andLike("companyAddr", "%" + offerInfoQuery.getCompanyAddr() + "%");
        }
        if (offerInfoQuery.getSalaryMode() != null) {
            example.and().andEqualTo("salaryMode", offerInfoQuery.getSalaryMode());
        }
        if (offerInfoQuery.getSalaryBasicStart() != null &&
                offerInfoQuery.getSalaryBasicEnd() != null) {
            example.and().andBetween("salaryBasic", offerInfoQuery.getSalaryBasicStart(),
                    offerInfoQuery.getSalaryBasicEnd());
        }
        if (offerInfoQuery.getSalaryRemark() != null) {
            example.and().andLike("salaryRemark", "%" + offerInfoQuery.getSalaryRemark() + "%");
        }
        if (offerInfoQuery.getAttachment() != null) {
            example.and().andLike("attachment", "%" + offerInfoQuery.getAttachment() + "%");
        }
        if (offerInfoQuery.getGmtCreateStart() != null &&
                offerInfoQuery.getGmtCreateEnd() != null) {
            example.and().andBetween("gmtCreate", offerInfoQuery.getGmtCreateStart(),
                    offerInfoQuery.getGmtCreateEnd());
        }
        if (offerInfoQuery.getCreateUserId() != null) {
            example.and().andLike("createUserId", "%" + offerInfoQuery.getCreateUserId() + "%");
        }
        if (offerInfoQuery.getGmtModifiedStart() != null &&
                offerInfoQuery.getGmtModifiedEnd() != null) {
            example.and().andBetween("gmtModified", offerInfoQuery.getGmtModifiedStart(),
                    offerInfoQuery.getGmtModifiedEnd());
        }
        if (offerInfoQuery.getModifiedUserId() != null) {
            example.and().andLike("modifiedUserId", "%" + offerInfoQuery.getModifiedUserId() + "%");
        }
        // 排序
        ExampleKit.setExampleOrder(example,offerInfoQuery.getOrders());
        return example;
    }

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public OfferInfoVO saveAndSend(OfferInfoAddDTO offerInfoAddDTO, TokenUser tokenUser) {
        // 转DO
        OfferInfoDO offerInfoDO = offerInfoAddDTO.to(OfferInfoDO.class);
        // 保存
        offerInfoDO = save(offerInfoDO, tokenUser.getSiteId(), tokenUser.getUserId());
        // 候选人offer信息存入redis
        redisTemplate.boundValueOps(CacheKeyKit.getOfferCacheKey(offerInfoDO.getId())).set(JSON.toJSONString(offerInfoDO), offerInfoDO.getExpiry(), TimeUnit.DAYS);
        // 发送邮件给候选人
//        Result<Boolean> result = sendOfferEmail(offerInfoDO, tokenUser);
//        if(!result.getSuccess()){
//            throw new HrException(HrConstants.OFFER_EMAIL_EXP);
//        }
        return offerInfoDO.to(OfferInfoVO.class);
    }

//    @Override
//    public Result<Boolean> sendOfferEmail(OfferInfoDO offerInfoDO, TokenUser tokenUser) {
//        // 生成员工录入信息页面链接
//        String empInitUrl = "";
//        try {
//            DES3Secure des3Secure = (DES3Secure) SecureFactory.getSecure(SecureType.DES3, HrConstants.EMP_3DES_KEY);
//            String offerInfoIdBase64 = des3Secure.getEncrypt2Base64(offerInfoDO.getId().getBytes());
//            String siteIdBase64 = des3Secure.getEncrypt2Base64(tokenUser.getSiteId().getBytes());
//            empInitUrl = HrConstants.EMP_INIT_URL + "?siteId=" + siteIdBase64 + "&offerInfoId=" + offerInfoIdBase64;
//        } catch (Exception e) {
//            e.printStackTrace();
//            return Result.fail(e.getMessage());
//        }
//        EmailDTO emailDTO = new EmailDTO();
//        List<String> toEmailList = new ArrayList<>();
//        toEmailList.add(offerInfoDO.getEmail());
//        EmailTemplateDO emailTemplateDO = emailTemplateDAO.findById(HrConstants.INFORMAL_OFFER_EMAIL_TEMP_ID);
//        DepInfoDO depInfoDO = depInfoDAO.selectByPrimaryKey(offerInfoDO.getDepId());
//        PositionInfoDO positionInfoDO = positionInfoDAO.selectByPrimaryKey(offerInfoDO.getPositionId());
//        Map<String, Object> subjectMap = new HashMap<>();
//        Map<String, Object> contentMap = new HashMap<>();
//        contentMap.put("name", offerInfoDO.getName());
//        contentMap.put("depName", depInfoDO.getName());
//        contentMap.put("positionName", positionInfoDO.getName());
//        contentMap.put("entryDate", offerInfoDO.getEntryDate());
//        contentMap.put("entryAddr", offerInfoDO.getEntryAddr());
//        contentMap.put("entryContact", offerInfoDO.getEntryContact());
//        contentMap.put("probation", offerInfoDO.getProbation());
//        contentMap.put("salaryBasic", offerInfoDO.getSalaryBasic());
//        contentMap.put("expiry", offerInfoDO.getExpiry());
//        contentMap.put("attachment", offerInfoDO.getAttachment());
//        contentMap.put("empInitUrl", empInitUrl);
//        emailDTO.setTemplateId(emailTemplateDO.getId().intValue());
//        emailDTO.setSenderEmail(HrConstants.OFFER_SENDER_EMAIL);
//        emailDTO.setToEmail(toEmailList);
//        emailDTO.setSubjectParams(subjectMap);
//        emailDTO.setContentParams(contentMap);
//        return sendEmail(emailDTO);
//    }
//
//    @Override
//    public Result<Boolean> sendEmail(EmailDTO emailDTO) {
//        EmailSendLogDO logDO = emailService.sendEmail(emailDTO);
//        if(logDO.getSuccess()){
//            return Result.success(Boolean.TRUE);
//        }
//        return Result.fail(logDO.getResult());
//    }

    @Override
    public OfferInfoVO getOfferInfoById(String offerInfoId, String siteId) {
        // 验证redis的offer信息
        String jsonStr = null;
        try {
            DES3Secure des3Secure = (DES3Secure) SecureFactory.getSecure(SecureType.DES3, HrConstants.EMP_3DES_KEY);
            String offerInfoIdStr = des3Secure.getDecrypt2Base64(offerInfoId.getBytes());
            jsonStr = redisTemplate.opsForValue().get(CacheKeyKit.getOfferCacheKey(offerInfoIdStr));
            if (jsonStr == null) {
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return JSON.parseObject(jsonStr, OfferInfoVO.class);
    }
}




